# -*- coding: utf-8 -*-
"""
@Time    : 2024/10/10 13:52 
@Author  : ZhangShenao 
@File    : account.py 
@Desc    : 账户类
"""
import time
from threading import Lock


class Account:
    """账户类"""

    def __init__(self, balance: int):
        """
        构造函数
        :param balance: 账户初始余额
        """

        self._balance = balance

        # 初始化锁,用于包含临界资源
        self._lock = Lock()

    def recharge(self, amount: int) -> None:
        """
        充值余额
        :param amount: 充值金额
        """

        # 加锁保护临界资源,保证线程安全
        self._lock.acquire()

        try:
            new_balance = self._balance + amount
            # 模拟账户充值耗时
            time.sleep(0.001)
            self._balance = new_balance
        except Exception:
            print("转账失败")
        finally:
            # 在finally块中释放锁资源
            self._lock.release()

    @property
    def balance(self) -> int:
        """
        查询账号余额
        :return: 余额
        """

        return self._balance
